// 初始化工序列表
const outerProcesses = [
    "上片", "淋漆（外圈）", "控漆1", "控漆2", "控漆3", "等待1",
    "预烘干", "喷漆", "等待2", "烘干1", "烘干2", "烘干3", "烘干4",
    "等待3", "可切换等待", "等待4", "等待5", "等待6", "等待7", "翻转"
];

const innerProcesses = [
    "上片", "淋漆（外圈）", "控漆1", "控漆2", "等待1", "预烘干",
    "喷漆", "等待2", "烘干1", "烘干2", "烘干3", "烘干4", "下片",
    "等待3", "等待4", "等待5", "等待6"
];

// 工序状态
let processStatus = {};
let simulationInterval = null;
let isSimulationRunning = false;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initPage();
    setupEventListeners();
});

// 初始化页面
function initPage() {
    displayProcesses('outerCircle', outerProcesses, true);
    displayProcesses('innerCircle', innerProcesses, false);
    // 初始化后刷新订单号显示
    refreshAllOrderDisplay();
}

// 展示工序
function displayProcesses(containerId, processes, isOuter) {
    const container = document.getElementById(containerId);
    // 调整半径以适应新的容器尺寸（使用百分比计算）
    const containerWidth = container.offsetWidth;
    const containerHeight = container.offsetHeight;
    // 使用不同的水平和垂直半径创建椭圆路径
    const radiusX = isOuter ? containerWidth * 0.47 : containerWidth * 0.5;
    const radiusY = isOuter ? containerHeight * 0.47 : containerHeight * 0.5;
    const centerX = containerWidth / 2;
    const centerY = containerHeight / 2;
    
    container.innerHTML = '';
    
    const totalSteps = processes.length;
    processes.forEach((process, index) => {
        const angle = (index / totalSteps) * 2 * Math.PI - Math.PI/2; // 从顶部开始
        // 使用椭圆方程计算位置
        const x = centerX + radiusX * Math.cos(angle);
        const y = centerY + radiusY * Math.sin(angle);
        
        const stepElement = document.createElement('div');
        stepElement.className = `process-step ${isOuter ? 'outer' : 'inner'}`;
        stepElement.style.left = `${x - 60}px`; // 调整位置避免重叠
        stepElement.style.top = `${y - 40}px`; // 调整位置避免重叠
        
        // 创建工序内容元素
        const contentContainer = document.createElement('div');
        contentContainer.className = 'step-content';
        
        const indexElement = document.createElement('div');
        // indexElement.className = 'step-index';
        // indexElement.textContent = index + 1;
        
        const nameElement = document.createElement('div');
        nameElement.className = 'step-name';
        nameElement.textContent = index + 1+":"+process;
        
        // 将索引和名称放入同一个容器
        contentContainer.appendChild(indexElement);
        contentContainer.appendChild(nameElement);
        
        const orderIdElement = document.createElement('div');
        orderIdElement.className = 'order-id';
        orderIdElement.textContent = ''; // 初始为空
        
        // 添加子元素到工序元素
        stepElement.appendChild(contentContainer);
        stepElement.appendChild(orderIdElement);
        
        stepElement.dataset.index = index;
        stepElement.dataset.isOuter = isOuter;
        
        // 根据工序类型添加特殊样式
        if (process.includes('等待')) {
            stepElement.classList.add('waiting');
        } else if (process.includes('淋漆') || process.includes('喷漆')) {
            stepElement.classList.add('painting');
        } else if (process.includes('烘干')) {
            stepElement.classList.add('drying');
        }
        
        container.appendChild(stepElement);
    });
    
    // 添加机器动画元素
    // addMachineElements(container, isOuter, radiusX, radiusY, centerX, centerY);
}

// 添加机器动画元素
function addMachineElements(container, isOuter, radiusX, radiusY, centerX, centerY) {
    const machine = document.createElement('div');
    machine.className = `machine ${isOuter ? 'outer-machine' : 'inner-machine'}`;
    
    // 随机位置，按照椭圆路径分布
    const angle = Math.random() * 2 * Math.PI;
    const x = centerX + (radiusX - 30) * Math.cos(angle);
    const y = centerY + (radiusY - 30) * Math.sin(angle);
    
    machine.style.left = `${x - 20}px`;
    machine.style.top = `${y - 20}px`;
    container.appendChild(machine);
}

// 设置事件监听器
function setupEventListeners() {
    document.getElementById('queryBtn').addEventListener('click', queryOrderStatus);
    document.getElementById('addOrderBtn').addEventListener('click', addSampleOrder);
    document.getElementById('startSimulationBtn').addEventListener('click', startSimulation);
    document.getElementById('stopSimulationBtn').addEventListener('click', stopSimulation);
    
    // 回车键查询
    document.getElementById('orderInput').addEventListener('keyup', function(event) {
        if (event.key === 'Enter') {
            queryOrderStatus();
        }
    });
}

// 查询订单状态
function queryOrderStatus() {
    const orderId = document.getElementById('orderInput').value.trim();
    const statusElement = document.getElementById('orderStatus');
    
    if (!orderId) {
        statusElement.innerHTML = '<span style="color: #ff5555;">请输入订单号</span>';
        return;
    }
    
    if (processStatus[orderId]) {
        const status = processStatus[orderId];
        let statusText = `订单： <strong>${orderId}</strong> <br/>`;
        
        if (status.outerIndex !== undefined && status.outerIndex >= 0) {
            statusText += `外圈：第 ${status.outerIndex + 1} 道工序 (${outerProcesses[status.outerIndex]})<br/>`;
        }
        
        if (status.innerIndex !== undefined && status.innerIndex >= 0) {
            if (status.outerIndex !== undefined && status.outerIndex >= 0) {
                // statusText += ' → ';
            }
            statusText += `内圈：第 ${status.innerIndex + 1} 道工序 (${innerProcesses[status.innerIndex]})`;
        }
        
        // 添加时间轴形式的工序历史信息
        if (status.processHistory && status.processHistory.length > 0) {
            statusText += '<br/>';
            statusText += '<div class="timeline">';
            
            // 倒序显示，最新的在最上面
            const reversedHistory = [...status.processHistory].reverse();
            reversedHistory.forEach((process, index) => {
                const processName = process.type === 'outer' ? 
                    outerProcesses[process.index] : 
                    innerProcesses[process.index];
                
                const enterTime = process.enterTime.toLocaleString('zh-CN');
                const isCurrent = !process.leaveTime;
                
                statusText += `<div class="timeline-item">
                    <div class="timeline-badge ${process.type}">${process.type === 'outer' ? '外' : '内'}</div>
                    <div class="timeline-panel ${isCurrent ? 'current-process' : ''}">
                        <div class="timeline-title">${process.type === 'outer' ? '外圈' : '内圈'}第${process.index + 1}道工序 (${processName})</div>
                        <div class="timeline-time">进入时间: ${enterTime}</div>`;
                
                if (process.leaveTime) {
                    const leaveTime = process.leaveTime.toLocaleString('zh-CN');
                    const duration = Math.round((process.leaveTime - process.enterTime) / 1000); // 转换为秒
                    statusText += `<div class="timeline-time">离开时间: ${leaveTime}</div>
                        <div class="timeline-duration">耗时: ${duration}秒</div>`;
                } else {
                    statusText += `<div class="timeline-duration">当前工序</div>`;
                }
                
                statusText += `</div></div>`;
            });
            
            statusText += '</div>';
        }
        
        statusElement.innerHTML = statusText;
        highlightCurrentProcess(orderId);
        
        // 显示订单号
        displayOrderOnProcess(orderId);
    } else {
        statusElement.innerHTML = `<span style="color: #ffaa55;">未找到订单 ${orderId} 的信息</span>`;
    }
    
    // 刷新所有订单号显示
    refreshAllOrderDisplay();
}

// 高亮显示当前工序并显示订单号
function highlightCurrentProcess(orderId) {
    // 清除所有高亮
    document.querySelectorAll('.process-step').forEach(step => {
        step.classList.remove('active');
    });
    
    // 为所有有订单的工序显示订单号
    Object.keys(processStatus).forEach(id => {
        const status = processStatus[id];
        if (!status) return;
        
        // 显示外圈工序的订单号
        if (status.outerIndex !== undefined && status.outerIndex >= 0) {
            const outerSteps = document.querySelectorAll('.process-step.outer');
            if (outerSteps[status.outerIndex]) {
                outerSteps[status.outerIndex].querySelector('.order-id').textContent = id;
                // 如果是当前查询的订单，则高亮显示
                if (id === orderId) {
                    outerSteps[status.outerIndex].classList.add('active');
                }
            }
        }
        
        // 显示内圈工序的订单号
        if (status.innerIndex !== undefined && status.innerIndex >= 0) {
            const innerSteps = document.querySelectorAll('.process-step.inner');
            if (innerSteps[status.innerIndex]) {
                innerSteps[status.innerIndex].querySelector('.order-id').textContent = id;
                // 如果是当前查询的订单，则高亮显示
                if (id === orderId) {
                    innerSteps[status.innerIndex].classList.add('active');
                }
            }
        }
    });
}

// 添加一个专门用于刷新所有订单号显示的函数
function refreshAllOrderDisplay() {
    // 清除所有订单号显示
    document.querySelectorAll('.process-step .order-id').forEach(element => {
        element.textContent = '';
    });
    
    // 为所有有订单的工序显示订单号
    Object.keys(processStatus).forEach(id => {
        const status = processStatus[id];
        if (!status) return;
        // 显示外圈工序的订单号
        if (status.outerIndex !== undefined && status.outerIndex >= 0) {
            const outerSteps = document.querySelectorAll('.process-step.outer');
            if (outerSteps[status.outerIndex]) {
                const orderIdElement = outerSteps[status.outerIndex].querySelector('.order-id');
                if (orderIdElement) {
                    orderIdElement.textContent = id;
                }
            }
        }
        
        // 显示内圈工序的订单号
        if (status.innerIndex !== undefined && status.innerIndex >= 0) {
            const innerSteps = document.querySelectorAll('.process-step.inner');
            if (innerSteps[status.innerIndex]) {
                const orderIdElement = innerSteps[status.innerIndex].querySelector('.order-id');
                if (orderIdElement) {
                    orderIdElement.textContent = id;
                }
            }
        }
    });
}

// 在对应工序上显示订单号
function displayOrderOnProcess(orderId) {
    const status = processStatus[orderId];
    if (!status) return;
    
    // 显示外圈工序的订单号
    if (status.outerIndex !== undefined && status.outerIndex >= 0) {
        const outerSteps = document.querySelectorAll('.process-step.outer');
        if (outerSteps[status.outerIndex]) {
            const orderIdElement = outerSteps[status.outerIndex].querySelector('.order-id');
            if (orderIdElement) {
                orderIdElement.textContent = orderId;
            }
        }
    }
    
    // 显示内圈工序的订单号
    if (status.innerIndex !== undefined && status.innerIndex >= 0) {
        const innerSteps = document.querySelectorAll('.process-step.inner');
        if (innerSteps[status.innerIndex]) {
            const orderIdElement = innerSteps[status.innerIndex].querySelector('.order-id');
            if (orderIdElement) {
                orderIdElement.textContent = orderId;
            }
        }
    }
    
    // 如果订单已完成所有工序，显示在待转移区
    if (status.outerIndex === -2 && status.innerIndex === -2) {
        const completedOrdersElement = document.querySelector('.completed-orders');
        if (completedOrdersElement) {
            // 检查是否已经添加了该订单
            let orderExists = false;
            completedOrdersElement.querySelectorAll('.order-item').forEach(item => {
                if (item.textContent === orderId) {
                    orderExists = true;
                }
            });
            
            // 如果不存在，则添加
            if (!orderExists) {
                const orderItem = document.createElement('div');
                orderItem.className = 'order-item';
                orderItem.textContent = orderId;
                completedOrdersElement.appendChild(orderItem);
            }
        }
    }
}

// 添加示例订单
function addSampleOrder() {
    const orderId = 'Order' + Math.floor(1000 + Math.random() * 9000);
    processStatus[orderId] = {
        processHistory: [] // 记录工序历史
    };

    // 添加到 outerIndex
    processStatus[orderId].outerIndex = 0;
    // 记录进入第一个外圈工序的时间
    processStatus[orderId].processHistory.push({
        type: 'outer',
        index: 0,
        enterTime: new Date()
    });


    document.getElementById('orderInput').value = orderId;
    
    // 显示订单号
    displayOrderOnProcess(orderId);
    
    // 查询并高亮显示当前订单
    queryOrderStatus();
    
    // 显示添加成功信息
    const statusElement = document.getElementById('orderStatus');
    statusElement.innerHTML = `<span style="color: #55ff55;">已添加模拟订单: ${orderId}</span>`;
}

// 开始模拟
function startSimulation() {
    if (isSimulationRunning) return;
    
    isSimulationRunning = true;
    simulationInterval = setInterval(() => {
        let hasUpdates = false;
        Object.keys(processStatus).forEach(orderId => {
            updateOrderStatus(orderId);
            hasUpdates = true;
        });
        
        // 如果有状态更新，刷新显示
        if (hasUpdates) {
            // 显示所有订单号
            Object.keys(processStatus).forEach(orderId => {
                displayOrderOnProcess(orderId);
            });
        }
        
        // 如果有查询的订单，高亮显示它
        const currentOrderId = document.getElementById('orderInput').value.trim();
        if (currentOrderId && processStatus[currentOrderId]) {
            highlightCurrentProcess(currentOrderId);
        }
    }, 2000);
    
    document.getElementById('orderStatus').innerHTML = '<span style="color: #55ff55;">模拟运行中...</span>';
}

// 停止模拟
function stopSimulation() {
    if (simulationInterval) {
        clearInterval(simulationInterval);
        simulationInterval = null;
        isSimulationRunning = false;
        document.getElementById('orderStatus').innerHTML = '<span style="color: #ff5555;">模拟已停止</span>';
    }
}

// 更新订单状态
function updateOrderStatus(orderId) {
    const status = processStatus[orderId];
    if (!status) return;
    
    const now = new Date();
    
    // 先清除该订单在所有工序上的显示
    clearOrderDisplay(orderId);
    
    // 更新工序历史记录，记录离开时间
    if (status.processHistory && status.processHistory.length > 0) {
        const lastProcess = status.processHistory[status.processHistory.length - 1];
        if (!lastProcess.leaveTime) {
            lastProcess.leaveTime = now;
        }
    }
    
    // 如果在外圈工序中，更新外圈
    if (status.outerIndex >= 0 && status.outerIndex < outerProcesses.length - 1) {
        status.outerIndex++;
        // 记录进入新工序的时间
        if (!status.processHistory) status.processHistory = [];
        status.processHistory.push({
            type: 'outer',
            index: status.outerIndex,
            enterTime: now
        });
    } 
    // 如果外圈已完成，开始内圈
    else if (status.outerIndex >= outerProcesses.length - 1 && status.innerIndex === undefined) {
        status.outerIndex = -1; // 标记外圈已完成
        status.innerIndex = 0;  // 开始内圈第一个工序
        // 记录进入内圈第一个工序的时间
        if (!status.processHistory) status.processHistory = [];
        status.processHistory.push({
            type: 'inner',
            index: status.innerIndex,
            enterTime: now
        });
    }
    // 如果在内圈工序中，更新内圈
    else if (status.innerIndex >= 0 && status.innerIndex < innerProcesses.length - 1) {
        status.innerIndex++;
        // 记录进入新工序的时间
        if (!status.processHistory) status.processHistory = [];
        status.processHistory.push({
            type: 'inner',
            index: status.innerIndex,
            enterTime: now
        });
    }
    // 如果内圈已完成，进入待转移区
    else if (status.innerIndex >= innerProcesses.length - 1) {
        status.outerIndex = -2; // 标记已完成所有工序
        status.innerIndex = -2; // 标记已完成所有工序
        // 记录离开最后一个工序的时间
        if (status.processHistory && status.processHistory.length > 0) {
            const lastProcess = status.processHistory[status.processHistory.length - 1];
            if (!lastProcess.leaveTime) {
                lastProcess.leaveTime = now;
            }
        }
    }
    // 如果订单已完成所有工序，重置
    else if (status.outerIndex === -2 && status.innerIndex === -2) {
        return;//不需要重新开始
        // 这里我们重置订单状态以持续演示
        // status.outerIndex = 0;
        // status.innerIndex = undefined; // 内圈尚未开始
        // // 清空历史记录并记录进入第一个工序的时间
        // status.processHistory = [{
        //     type: 'outer',
        //     index: 0,
        //     enterTime: now
        // }];
    }
    
    // 更新后显示订单号到新工序
    displayOrderOnProcess(orderId);
}

// 清除订单在所有工序上的显示
function clearOrderDisplay(orderId) {
    const allOrderIdElements = document.querySelectorAll('.process-step .order-id');
    allOrderIdElements.forEach(element => {
        if (element.textContent === orderId) {
            element.textContent = '';
        }
    });
    
    // 同时清除待转移区的订单显示
    const completedOrdersElement = document.querySelector('.completed-orders');
    if (completedOrdersElement) {
        completedOrdersElement.querySelectorAll('.order-item').forEach(item => {
            if (item.textContent === orderId) {
                item.remove();
            }
        });
    }
}

function handleOrder(orderId) {
    // 检查订单是否已经在处理中
    if (isOrderProcessing(orderId)) {
        console.log(`Order ${orderId} is already being processed.`);
        return;
    }

    // 根据业务逻辑决定首先在外圈还是内圈处理
    if (shouldStartWithOuterCircle(orderId)) {
        startOuterCircleProcess(orderId);
    } else {
        startInnerCircleProcess(orderId);
    }
}

function isOrderProcessing(orderId) {
    // 检查订单是否在外圈或内圈工序中
    return isOrderInOuterCircle(orderId) || isOrderInInnerCircle(orderId);
}

function isOrderInOuterCircle(orderId) {
    // 实现检查订单是否在外圈工序中的逻辑
    // 示例：
    return outerCircleProcesses.includes(orderId);
}

function isOrderInInnerCircle(orderId) {
    // 实现检查订单是否在内圈工序中的逻辑
    // 示例：
    return innerCircleProcesses.includes(orderId);
}

function shouldStartWithOuterCircle(orderId) {
    // 根据业务规则决定订单是否应该首先在外圈处理
    // 示例：所有订单都先在外圈处理
    return true;
}

function startOuterCircleProcess(orderId) {
    // 将订单添加到外圈工序
    outerCircleProcesses.push(orderId);
    // 更新UI等相关操作
    updateOuterCircleUI();
}

function startInnerCircleProcess(orderId) {
    // 将订单添加到内圈工序
    innerCircleProcesses.push(orderId);
    // 更新UI等相关操作
    updateInnerCircleUI();
}

// 页面卸载时清理
window.addEventListener('beforeunload', function() {
    if (simulationInterval) {
        clearInterval(simulationInterval);
    }
});